package com.betterwood.dragon.worms;

import java.util.ArrayList;
import java.util.List;

import com.betterwood.dragon.entity.Result;
import com.betterwood.dragon.entity.Site;
import com.betterwood.dragon.entity.dto.SearchDTO;
import com.betterwood.dragon.utils.TimeUtil;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class YF {
    // 扬帆密码失效
    public static String login(Site site) {
        log.info("#########################################");
        log.info("############START LOGIN TO YF############");
        String contextState = "EMPTY";

        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
            BrowserContext context = browser.newContext();

            // Open new page
            Page page = context.newPage();

            page.navigate("https://mall.gzyfyy.cn/login.html");
            page.click("#user");
            // Fill input[name="userName"]
            page.fill("#user", site.getUserName());
            // Click input[name="password"]
            page.click("#pass");
            // Fill input[name="password"]
            page.fill("#pass", site.getPassWord());

            // page.pause();
            // Click text=登 录
            // page.waitForNavigation(new
            // Page.WaitForNavigationOptions().setUrl("http://b2b.gzyfyy.cn/_shop/default/index.shtml"),
            // () ->
            page.waitForNavigation(() -> {
                page.click("text=登录 记住密码 注册 忘记密码 使用其他方式登录： >> button");
                // page.click("text=登录");
            });
            // ---------------------

            contextState = context.storageState();
            // log.info(contextState);
            log.info("############END OF LOGIN TO YF#############");

        } catch (RuntimeException e) {
            e.printStackTrace();

        }
        return contextState;
    }

    public static List<Result> fetchProduct(Site site, SearchDTO search) {
        log.info("#######################################");
        log.info("############START FETCH FROM YF########");

        // List<Result> res = getList(site, search);

        List<Result> initList = new ArrayList<>();

        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));

            String storageState = site.getLoginInfo();

            BrowserContext context = browser.newContext(new Browser.NewContextOptions().setStorageState(storageState));

            // Open new page
            Page page = context.newPage();

            // Go to http://www.fuji-pharm.cn/
            // page.pause();

            page.navigate(site.getSiteUrl());
            // log.info("**********");
            // log.info(search.getKeywordStr());
            // log.info("**********");

            page.fill(":nth-match(.el-input__inner, 2)", search.getKeywordStr());
            // page.click("text=搜索");

            page.waitForNavigation(() -> {
                page.click(":nth-match(#searchButtom, 2)");
                // page.click("text=搜索");
            });

            page.waitForTimeout(3500);

            String content = page.innerHTML("#allsea_comm");
            initList = getList(content, search, site);

            String pager = page.innerHTML("#DivPages");
            Document pagerDoc = Jsoup.parseBodyFragment(pager);
            Element rightArrow = pagerDoc.getElementById("next");
            if (ObjectUtil.isNull(rightArrow)) {
                log.info("NO PAGER HERE");
                return initList;
            }

            boolean hasNext = !rightArrow.classNames().contains("disable");
            log.info(Boolean.toString(hasNext));
            List<Result> otherList = new ArrayList<>();

            while (hasNext) {
                page.click("#next");
                page.waitForTimeout(3500);

                content = page.innerHTML("#allsea_comm");

                otherList = getList(content, search, site);
                initList.addAll(otherList);

                pager = page.innerHTML("#DivPages");
                if (!page.isVisible("#DivPages")) {
                    hasNext = false;
                    log.info("EMPTY, BREAK HERE!");
                    break;
                }

                pagerDoc = Jsoup.parseBodyFragment(pager);
                rightArrow = pagerDoc.getElementById("next");
                hasNext = !rightArrow.classNames().contains("disable");
            }

            // log.info(content);

        } catch (RuntimeException e) {
            e.printStackTrace();
            log.info("WORM YF FAILED");
        }

        log.info("END OF fetch product");
        log.info("**************FOUND NEW PRODUCTS!!!******************");
        log.info(Integer.toString(initList.size()));
        log.info("**************FOUND NEW PRODUCTS!!!******************");
        return initList;
    }

    public static List<Result> getList(String content, SearchDTO search, Site site) {

        Document doc = Jsoup.parseBodyFragment(content);
        Element body = doc.body();
        Elements lis = body.getElementsByTag("li");
        List<Result> list = new ArrayList<>();

        for (Element li : lis) {

            // log.info("***************************************************");
            String pName = li.getElementsByClass("flex_name").first().text();

            // log.info("商品名是:" + pName);
            Elements els = li.getElementsByClass("tag_blue_n");
            String sourcePriceClean = "0.0";
            Double priceDouble = 0.0;

            if (els.size() > 0) {
                String sourcePrice = els.first().text();
                String sourcePriceStr = StrUtil.split(sourcePrice, "")[1];
                sourcePriceClean = StrUtil.removePrefix(sourcePriceStr, "￥");
                priceDouble = NumberUtil.isNumber(sourcePriceClean) ? Double.parseDouble(sourcePriceClean) : 0;
            }

            // log.info("价格是:" + sourcePriceClean);
            // log.info("数字价格是:" + priceDouble.toString());

            // Elements els = li.getElementsByClass("p-caption");
            // Element item = els.first().getElementsByTag("a").first();
            // String pName = item.text();
            // String orderUrl = item.attributes().get("href");

            String sourceProp = li.getElementsByClass("specs").first().text();

            String prop = StrUtil.split(sourceProp, "：")[1];
            // log.info("商品规格是:" + prop);

            String maker = li.getElementsByClass("factory_name").first().text();
            // log.info("商品制造厂是:" + maker);

            // String orderUrl = li.getElementsByTag("a").get(0).attributes().get("href");

            // log.info("商品名是:" + pName);
            // log.info("商品规格是:" + prop);
            // log.info("制造商是:" + maker);
            // log.info("价格是:" + sourcePriceClean);
            // log.info("数字价格是:" + priceDouble);

            String orderUrl = li.getElementsByTag("a").get(0).attributes().get("href");
            // log.info("商品购买URL是:" + orderUrl);

            Result re = new Result();

            re.setProductName(pName);
            re.setMaker(maker);
            re.setProp(prop);
            // re.setOrderUrl(StrUtil.concat(true, site.getSiteUrl(), orderUrl));
            re.setScanTime(TimeUtil.currentTime());
            re.setSearchId(search.getId());
            re.setSiteName("扬帆");
            re.setOrderUrl(StrUtil.concat(true, site.getBaseUrl(), orderUrl));

            re.setKeywordStr(search.getKeywordStr());
            // // // // // re.setSiteId("");
            re.setSiteNo("YF");
            re.setScanPrice(sourcePriceClean);

            re.setPrice(priceDouble);
            re.setStatus(0);
            list.add(re);
        }

        // return "SUCCESS";
        // log.info("WORM YF SUCCESS");

        return list;
    }
}
